package com.sam.mybatisplus.support;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页工具类
 * @author sam
 * @param <T>
 */
@Data
@ApiModel(value = "分页数据", description = "分页数据")
public class PageResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 总记录数
     */
    @ApiModelProperty(value = "总记录数,默认0")
    private Long total = 0L;
    /**
     * 结果集
     */
    @ApiModelProperty(value = "返回结果集")
    private List<T> items = new ArrayList<>();

    /**
     * 当前页码
     */
    @ApiModelProperty(value = "当前页码,默认1")
    private int pageNum=1;

    /**
     * 每页显示记录数
     */
    @ApiModelProperty(value = "每页显示记录数,默认10")
    private int pageSize=10;

    /**
     * 实际记录数
     */
    @ApiModelProperty(value = "实际记录数")
    private int pages;
    /**
     * 总页数
     */
    @ApiModelProperty(value = "总页数,默认1")
    private int pageCount = 1;

    /**
     * 是否为第一页
     */
    @ApiModelProperty(value = "是否为第一页")
    private boolean firstPage;

    /**
     * 是否为最后一页
     */
    @ApiModelProperty(value = "是否为最后一页")
    private boolean lastPage;

    /**
     * 是否有上一页
     */
    @ApiModelProperty(value = "是否有上一页")
    private boolean hasPrePage;

    /**
     * 是否有下一页
     */
    @ApiModelProperty(value = "是否有下一页")
    private boolean hasNextPage;

    public PageResult(){}

    public PageResult(List<T> list, Long total, int pageNum, int pageSize) {
        if (!list.isEmpty()){
            this.items = list;
        }
        this.pages = this.items.size();
        init(total,pageNum,pageSize);
    }

    /**
     * 计算分页
     * @param total
     * @param pageNum
     * @param pageSize
     */
    private void init(long total,int pageNum, int pageSize){
        //设置基本参数
        this.total = total;
        this.pageSize = pageSize;
        this.pageCount = (int)((this.total-1)/this.pageSize+1);

        //根据输入可能错误的当前号码进行自动纠正
        if (pageNum<1){
            this.pageNum=1;
        }else if (pageNum > this.pageCount){
            this.pageNum = this.pageCount;
        }else{
            this.pageNum = pageNum;
        }

        judgePageBoudary();
    }

    /**
     * 判定页面边界
     */
    private void judgePageBoudary(){
        firstPage = pageNum == 1;
        lastPage = pageNum == pageCount && pageNum!=1;
        hasPrePage = pageNum!=1;
        hasNextPage = pageNum!=pageCount;
    }
}